//
//  BN_SchoolActivities.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-15.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_SchoolActivities.h"
#import "NurserySchoolCellTableViewCell.h"

@implementation BN_SchoolActivities {
    NSArray *titleArr_;
    NSArray *contentArr_;
    NSArray *timeArr_;
}

- (id)init {
    if (self = [super init]) {
        
        // 帮助类
        _helper = [[BN_KinderGartenHelper alloc]init];
        
        // 网络数据数组
        self.netArr = [[NSMutableArray alloc]init];
        
        [self requestNetData];
    }
    return self;
}


- (void)toSchoolReloadList:(School_ReloadList)reloadList {
    self.reloadList = reloadList;
}

- (void)activityRefrsh {
    if (!_helper) {
        _helper = [[BN_KinderGartenHelper alloc]init];
    }
    if ([self respondsToSelector:@selector(requestNetData)]) {
        [self requestNetData];
    }
}

#pragma mark UITableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NurserySchoolCellTableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.netArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"NurserySchoolCellTableViewCell";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([NurserySchoolCellTableViewCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        nibsRegistered = YES;
    }
    NurserySchoolCellTableViewCell *cell = (NurserySchoolCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    cell.tag = indexPath.section;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    // 重用BUG
    cell.contImageView.image = [UIImage imageNamed:@""];
    
    // 顶部分割线视图
    UILabel *titleLabel = (UILabel *)[cell.dividerView viewWithTag:402];
    if (![_netArr[indexPath.section][@"actiDate"] isEqual:[NSNull null]]) {
        NSString *dateStr = _netArr[indexPath.section][@"actiDate"];
        NSRange rang = NSMakeRange(0, 19);
        NSString *strRang = [dateStr substringWithRange:rang];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [formatter setTimeZone:timeZone];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *dateTime = [formatter dateFromString:strRang];
        titleLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
        [cell initDividerView];
    }
    
    // 标题
    if (![self.netArr[indexPath.section][@"actiSubj"] isEqual:[NSNull null]]) {
        cell.titleLabel.text = self.netArr[indexPath.section][@"actiSubj"];
    }
    
    // 图片信息
    NSString *fileTUrlStr = nil;
    NSArray *files = self.netArr[indexPath.section][@"files"];
    if (files.count != 0) {
        fileTUrlStr = files[0][@"fileTUrl"];
        fileTUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:fileTUrlStr];
        NSURL *imgUrl = [NSURL URLWithString:fileTUrlStr];
        [cell.contImageView setImageWithURL:imgUrl placeholderImage:nil];
    }

    // 文字内容
    if (![self.netArr[indexPath.section][@"actiCont"] isEqual:[NSNull null]]) {
        NSString *contStr = FORMAT_STR(self.netArr[indexPath.section][@"actiCont"]);
#warning 暂时限制一下文字格式
        if (contStr.length > 18) {
            NSRange rang = NSMakeRange(0, 18);
            NSString *strRang = [contStr substringWithRange:rang];
            strRang = [strRang stringByAppendingString:@"..."];
            cell.contLabel.text = strRang;
        }else {
            cell.contLabel.text = contStr;
        }
    }else {
        cell.contLabel.text = @"暂无介绍";
    }
    cell.activityId = [NSString stringWithFormat:@"%@",self.netArr[indexPath.section][@"actiId"]];
    [cell toGroup];
    [cell.titleLabel sizeToFit];
    [cell.contLabel sizeToFit];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark
#pragma mark 网络请求
- (void)requestNetData {

    __weak typeof(self) weakSelf = self;
    _helper.queryActionListCompleteHandler = ^(id result,NSString* errorMessage){
        //update by jason yan 2014-05-30
        if (errorMessage) {
            [LZCHINT title:errorMessage type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            if (weakSelf) {
                weakSelf.reloadList(NO,NO,nil);
            }
        }
        if (result) {
            if (weakSelf) {
                weakSelf.netArr = (NSMutableArray *)result;
                weakSelf.reloadList(YES,NO,nil);
            }
        }
    };
    [_helper refreshActionList];
}

- (void)activityModelDataRemove:(NSString *)result {
    NSInteger tag = [result integerValue];
    [self.netArr removeObjectAtIndex:tag];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:tag];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.reloadList(NO,YES,indexArray);
}

#pragma mark
#pragma mark 刷新类

- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self requestNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // NSLog(@"%@----刷新完毕", refreshView.class);
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            // NSLog(@"%@----切换到：普通状态", refreshView.class);
            break;
            
        case MJRefreshStatePulling:
            // NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
            break;
            
        case MJRefreshStateRefreshing:
            // NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
            break;
        default:
            break;
    }
}

- (void)dealloc
{
    [_helper cancelQueryActionList];
    _helper = nil;
    NSLog(@"学校活动Modal释放...");
}

@end
